package cn.cqs.redisitem.utils;


import com.google.common.base.Preconditions;
import com.google.common.hash.Funnel;

import java.io.Serializable;

public class BloomFilterHelper<T> implements Serializable {
    private long bitSize;
    private int numHashFunctions;
    private Funnel<T> funnel;
    public BloomFilterHelper(Funnel<T> funnel, int expectedInsertions, double fpp) {
        Preconditions.checkArgument(funnel != null, "funnel不能为空");
        this.funnel = funnel;
        bitSize = optimalNumOfBits(expectedInsertions, fpp);
        numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, bitSize);
    }




    /**
     * 计算Hash函数个数
     * @param expectedInsertions
     * @param bitSize
     * @return
     */
   private static int optimalNumOfHashFunctions(long expectedInsertions, long bitSize) {
        return Math.max(1, (int)Math.round((double)bitSize / (double)expectedInsertions * Math.log(2.0D)));
    }

    /**
     *bit数组长度
     * @param expectedInsertions 预期值
     * @param fpp 误差率
     * @return
     */
   private static long optimalNumOfBits(long expectedInsertions, double fpp) {
        if (fpp == 0.0D) {
            fpp = 4.9E-324D;
        }
        return (long)((double)(-expectedInsertions) * Math.log(fpp) / (Math.log(2.0D) * Math.log(2.0D)));
    }





}
